package com.factory.code.common.helper;

import cn.hutool.core.io.FileUtil;
import com.factory.code.service.model.TreeNodeModel;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yinyansheng
 */
public class FilePathHelper {

    public static String getDownloadPath() {
        String userDirPath = System.getProperty("user.dir");
        return userDirPath.concat("/downloads/");
    }

    public static TreeNodeModel tree(String directoryPath) {
        if (FileUtil.exist(directoryPath) && !FileUtil.isDirectory(directoryPath)) {
            throw new RuntimeException("directory not exists :" + directoryPath);
        }

        TreeNodeModel root = new TreeNodeModel(new File(directoryPath));
        tree(directoryPath, root);
        return root;
    }

    private static void tree(String path, TreeNodeModel parent) {
        if (!FileUtil.isDirectory(path) || FileUtil.isEmpty(new File(path))) {
            return;
        }
        List<TreeNodeModel> list = new ArrayList<>();
        for (File file : FileUtil.ls(path)) {
            TreeNodeModel treeNodeModel = new TreeNodeModel(file);
            list.add(treeNodeModel);
            tree(file.getPath(), treeNodeModel);
        }
        parent.setChildren(list);
    }


    /**
     * 获取系统文件路径格式
     */
    public static String getSystemPathFormat(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return "";
        }
        filePath = filePath.replace("\\", File.separator);
        filePath = filePath.replace("/", File.separator);
        return filePath;
    }

    public static boolean judgeFilePath(String filePath) {
        String systemFilePage = getSystemPathFormat(filePath);
        if (StringUtils.isEmpty(systemFilePage)) {
            return false;
        }
        if (!systemFilePage.contains(File.separator + File.separator)) {
            return true;
        }
        return false;

    }
}
